package com.zhu.controller;

import com.zhu.bean.Street;
import com.zhu.bean.Type;
import com.zhu.bean.User;
import com.zhu.service.StreetService;
import com.zhu.service.TypeService;
import com.zhu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StreetService streetService;
    @Autowired
    private TypeService typeService;

    @RequestMapping("/checkName.do")
    public void checkName(String nickName, HttpServletResponse response) throws IOException {
        User user = userService.findByName(nickName);
        if (user != null){
            response.getWriter().print("true");
        }else {
            response.getWriter().print("false");
        }
    }
    @RequestMapping("/regUser.do")
    public String regUser(User user) {
        int i = userService.addUser(user);
        if (i > 0){
            return "index.html";
        }
        return "error.html";
    }
    @RequestMapping("/login.do")
    public ModelAndView login(User user , HttpSession session){
        boolean b = userService.loginUser(user);
        ModelAndView mv = new ModelAndView();
        if (b){
            session.setAttribute("nickName",user.getNickName());
            List<Street> streetList = streetService.getAll();
            List<Type> types = typeService.getAll();
            session.setAttribute("types",types);
            session.setAttribute("streetList",streetList);
            mv.setViewName("redirect:/page/list.jsp");
            return mv;
        }
        mv.setViewName("redirect:index.html");
        return mv;
    }

}
